<template>
  <div class="component-upload-image">
    <elImageViewer :z-index="9999"  v-if="dialogVisible" :on-close="closeViewer" :url-list="urlList"/>

    <el-upload
      action=""
      list-type="picture-card"
      :on-success="handleUploadSuccess"
      :before-upload="handleBeforeUpload"
      :limit="limitValue"
      :on-exceed="handleExceed"
      name="file"
      :on-remove="handleRemove"
      :show-file-list="true"
      :file-list="fileList"
      :disabled="isShow"
      :on-preview="handlePictureCardPreview"
      :class="{hide: this.fileList.length >= this.limitValue}"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
<!--    <el-button @click="guideClick" size="mini" style="margin-top: 10px" v-if="!isVideo && sampleImg != null && sampleImg.length > 0">示例照片</el-button>-->
    <!-- 上传提示 -->
    <div slot="tip" v-if="showTip" style="color: red;white-space: pre-wrap;line-height: 15px;margin-top: 5px">
      <span style="font-size: 10px">{{tip}}</span>
    </div>

<!--    <el-dialog-->
<!--      :visible.sync="dialogVisible"-->
<!--      title="预览"-->
<!--      append-to-body-->
<!--    >-->
<!--      <img-->
<!--        :src="dialogImageUrl"-->
<!--        style="display: block; max-width: 100%; margin: 0 auto"-->
<!--      />-->
<!--    </el-dialog>-->
  </div>
</template>

<script>
// import { getToken } from "@/utils/auth";
import * as utils from '@/utils/woka'
import elImageViewer from 'element-ui/packages/image/src/image-viewer'
import * as qiniu from "qiniu-js";

export default {
  props: {
    value: [String, Object, Array],
    // 图片数量限制
    limit: {
      type: Number,
      default: 1,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["png", "jpg", "jpeg"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    },
    tip: {
      type: String,
      default: ''
    },
    guideImage: {
      type: String,
      default: ''
    },
    // sampleImg: {
    //   type: Array,
    //   default: []
    // },
    id: {
      type: String,
      default: ''
    },
    // 是否只能查看
    isShow: {
      type: Boolean,
      default: false
    },
    token: {
      type: String,
      default: ''
    },
    isVideo: {
      type: Boolean,
      default: false
    },
    index: {
      type: Number,
      default: 0
    },
    baseUrl: {
      type: String,
      default: ''
    },
    //图片类型
    titleLabel: {
      type: String,
      default: ''
    },
    documentType: {
      type: String,
      default: 'gh_assess'
    }
  },
  components:{ elImageViewer },
  data() {
    return {
      urlList: [],
      dialogImageUrl: "",
      videoType: ['avi','mp4','3gp','wmv','rmvb','mov','webm','ogg'],
      dialogVisible: false,
      hideUpload: false,
      // baseUrl: 'http://rc61zjdbf.hn-bkt.clouddn.com/',
      fileList: [],
      limitValue: 1,
    };
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          // 首先将值转为数组
          const isArray = Array.isArray(val);
          if (!isArray) {
            val.url = val.pic_url;
            this.fileList = [val]
          } else {
            this.fileList = val
          }
        } else {
          this.fileList = [];
          return [];
        }
      },
      deep: true,
      immediate: true
    },
    isShow: {
      handler(val) {
        if (val) {
          // this.$emit('update:isShowTip',false)
          // this.$emit('update:limit',this.fileList.length)
          this.limitValue = this.fileList.length
        }
      },
      deep: true,
      immediate: true
    },
    limit: {
      handler(val) {
        this.limitValue = val
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  created() {
    if (this.isShow) {
      this.limitValue = this.fileList.length
    }
  },
  methods: {
    // 删除图片
    handleRemove(file, fileList) {
      const findex = this.fileList.map(f => f.name).indexOf(file.name);
      if(findex > -1) {
        this.fileList.splice(findex, 1);
        this.$emit("input", this.fileList);
        this.successUpload(this.fileList)
      }
    },
    // 上传成功回调
    handleUploadSuccess(res) {
    },
    successUpload(val) {
      this.$emit("success", val);
    },
    // 上传前loading加载
    handleBeforeUpload(file) {
      let isImg = false;
      let fileExtension = ""
      if (file.name.lastIndexOf(".") > -1) {
        fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        fileExtension = fileExtension.toLowerCase()
      }
      let type = this.fileType;
      if (this.isVideo) {
        type = this.videoType
      }
      if (type.length) {
        isImg = type.some(type => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      }
      if (!isImg) {
        let message = `请正确上传图片不文件，当前文件格式${fileExtension}`
        if (this.isVideo) {
          message = `请上传视频文件，当前文件格式${fileExtension}`
        }
        // `文件格式不正确, 请上传${type.join("/")}格式文件!当前文件格式`
        this.$message.error(
          message
        );
        return false;
      }
      const time = new Date()
      const current = time.getTime()/1000;
      const fileDic = utils.parseTime(time,'/{y}/{m}/{d}/')
      let key = `${this.documentType}${fileDic}${current.toFixed(0)}${file.name.replaceAll('/','')}`;
      const config = {
        useCdnDomain: true,
        region: qiniu.region.z1,
        concurrentRequestLimit: 1000,
      };
      //上传图片
      this.loading = this.$loading({
        lock: true,
        text: "上传中",
        background: "rgba(0, 0, 0, 0.7)",
      });
      if (!this.isVideo) {
        utils.compressAccurately(file,900).then(response => {
          this.dealwithImage(response,key,config)
        })
      } else {
        this.dealwithImage(file,key,config)
      }
      return false
    },
    dealwithImage(file, key, config) {
      var observable = qiniu.upload( file, key, this.token, config);
      const _this = this;
      var observer = {
        next(res) {
          var { percent } = res.total;
          _this.loading.setText("上传中" + parseFloat(percent).toFixed(2) + '%')
        },
        error(err) {
          console.log(err);
        },
        complete(res) {
          _this.loading.close();
          if (_this.fileList == null || _this.fileList == undefined) {
            _this.fileList = []
          }
          _this.fileList.push({ PhotoID: _this.id,
            url: _this.baseUrl + res.key,name:res.key,
            category: _this.titleLabel,
            index:_this.index});
          _this.$emit("input", _this.fileList);
          _this.successUpload(_this.fileList)
        },
      };
      var subscription = observable.subscribe(observer);
    },

    // 文件个数超出
    handleExceed() {
      this.$message.error(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // // 上传失败
    // handleUploadError() {
    //   this.$message({
    //     type: "error",
    //     message: "上传失败",
    //   });
    //   this.loading.close();
    // },
    // 预览
    handlePictureCardPreview(file) {
      this.urlList = this.fileList.map(item => {
        return this.baseUrl + item.name
      })
      this.dialogVisible = true;
    },
    guideClick() {
      // if (Array.isArray(this.sampleImg)) {
      //   this.urlList = this.sampleImg.map(item => {
      //     return "https://" + item.ImgUrl
      //   })
      // } else  {
      //   this.urlList = ["https://" + this.sampleImg]
      // }
      //
      // this.dialogImageUrl = this.guideImage;
      // this.dialogVisible = true;
    },
    closeViewer() {
      this.dialogVisible = false;
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i].url.replace(this.baseUrl, "") + separator;
      }
      return strs != '' ? strs.substr(0, strs.length - 1) : '';
    }
  }
};
</script>
<style scoped lang="scss">
// .el-upload--picture-card 控制加号部分
::v-deep.hide .el-upload--picture-card {
  display: none;
}
// 去掉动画效果
::v-deep .el-list-enter-active,
::v-deep .el-list-leave-active {
  transition: all 0s;
}

::v-deep .el-list-enter, .el-list-leave-active {
  opacity: 0;
  transform: translateY(0);
}
</style>

